#include <vector>
#include <iostream>
#include <stack>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

/*
 *  二叉树后续遍历的迭代法，解决了一个误区
 *   这道题并不是很难，但一个小误会让我明白一个误区，这个TreeNode既然已经在堆中申请过一块空间并且它的父节点指向它了，不用delete它就会
 *   一直存在不会销毁，并不是简单把root置空它就销毁掉
 * */

class Solution {
public:
    vector<int> postorderTraversal(TreeNode *root) {
        vector<int> res;
        if (root == nullptr) {
            return res;
        }

        stack<TreeNode *> stk;
        TreeNode *prev = nullptr;
        while (root != nullptr || !stk.empty()) {
            while (root != nullptr) {
                stk.emplace(root);
                root = root->left;
            }
            root = stk.top();
            stk.pop();
            if (root->right == nullptr || root->right == prev) {
                res.emplace_back(root->val);
                prev = root;
                root = nullptr;
            } else {
                stk.emplace(root);
                root = root->right;
            }
        }
        return res;
    }
};

int main() {
    TreeNode root(1);
    TreeNode right(2);
    TreeNode right_left(3);
    root.right = &right;
    right.left = &right_left;
    Solution solution;
    auto result = solution.postorderTraversal(&root);
    for (auto it = result.begin(); it != result.end(); ++it) {
        cout << *it << " ";
    }
    cout << endl;
    return 0;
}